package com.market.cash.ui.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import com.market.cash.R
import com.market.cash.base.app.CashRootStackManager
import com.market.cash.databinding.CashLicenseViewBinding
import com.market.cash.databinding.CashLoginBinding
import com.market.cash.pro.ProActivity
import com.market.cash.ui.presenter.CashRootLoginPresenter
import com.market.cash.ui.view.ICashRootLoginView
import com.market.cash.utils.CashRootBarUtil
import com.market.cash.utils.CashRootImageUtil
import com.market.cash.utils.event.CashRootEventType
import com.market.cash.utils.helper.CashRootCustomConfigsHelper
import com.market.cash.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/17 16:48
 * @Annotation：登录
 */
class LoginActivity: ProActivity(),ICashRootLoginView {
    lateinit var binding: CashLoginBinding
    private var presenter: CashRootLoginPresenter? = null

    override fun getCashRootRootView(): View? {
        binding = CashLoginBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initCashRootView() {
        CashRootBarUtil.setStatusBarLightMode(this, false)
        binding.titleBarLayout.setPadding(0,CashRootBarUtil.getStatusBarHeight(),0,0)

        //关闭所有页面
        CashRootStackManager.finishAllActivity(LoginActivity::class.java)
        checkLoginBtnState()
    }

    override fun initCashRootListener() {
        //客服
        binding.imgKefu.setOnClickListener {
            KefuActivity.start(this,"Login Page")
        }

        binding.editMobile.setOnFocusChangeListener { v, hasFocus ->
            when(hasFocus){
                true -> {

                }
                else -> {
                    addCashRootEventPoint(CashRootEventType.FORM.CASHROOT_FORM_LOGIN_MOBILE, getMobile())
                }
            }
        }
        //电话号码入框监听
        binding.editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                checkLoginBtnState()
            }
        })
        binding.editMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.editMobile.clearFocus()
                true
            }
            false
        }

        //隐私政策切换
        binding.checkBox.setOnCheckedChangeListener { _, isChecked ->
            checkLoginBtnState()
            when (isChecked) {
                true -> {
                    addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_LOGIN_PRIVACY_AGREE)
                }
                false -> {
                    addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_LOGIN_PRIVACY_DENY)
                }
            }
        }

        //登录
        binding.btnNext.setOnClickListener {
            addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_LOGIN_NEXT)
            onHideSoftInput(binding.editMobile)
            presenter!!.requestLoginAction()
        }

        //隐私协议
        binding.textPrivacyPolicy.setOnClickListener {
            val showTitle = getString(R.string.privacy_policy_title)
            val linkUrl = CashRootCustomConfigsHelper.getCashRootPrivacyPolicyLink()
            WebViewActivity.start(this,showTitle, linkUrl)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initCashRootData() {
        presenter = CashRootLoginPresenter(this)
        binding.textZoneCode.text = "+${SharedHelper.getCashRootSPString(SharedHelper.CashRoot_SPKEY.CASHROOT_TIMEZONE_CODE)}"

        val showText = String.format(getString(R.string.login_privacy_policy),getString(R.string.privacy_policy_title))
        val spString = SpannableString(showText)
        val start = showText.indexOf(getString(R.string.privacy_policy_title))
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#343434")), start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //添加下划线
        spString.setSpan(UnderlineSpan(), start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textPrivacyPolicy.text = spString

        //牌照信息
        if (!CashRootCustomConfigsHelper.isCashRootShowLicense()){
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.visibility = View.VISIBLE
            val licenseInfo = CashRootCustomConfigsHelper.getCashRootLicenseInfo()
            if (licenseInfo != null) {
                CashRootImageUtil.instance.loadImageUrl(this, binding.imgLicenseLogo, licenseInfo.optString("logo"))
                val desc = licenseInfo.optString("desc")
                val companyName = licenseInfo.optString("companyName")
                binding.textLicenseInfo.text = desc
                binding.textCompanyName.text = companyName
            }
        }
    }

    /**
     * 设置登录按钮状态
     */
    private fun checkLoginBtnState() {
        if (binding.checkBox.isChecked && getMobile().isNotEmpty()) {
            binding.btnNext.isEnabled = true
        } else {
            binding.btnNext.isEnabled = false
        }
    }

    /**
     * 获取电话号码
     */
    override fun getMobile(): String {
        return binding.editMobile.text.toString().trim()
    }

    override fun showLoginFailure(data: JSONObject) {
    }

    override fun showMainPage() {
        onIntent(MainActivity::class.java)
        finish()
    }

    override fun onStart() {
        super.onStart()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_LOGIN_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_LOGIN_END)
    }
}